/*
* $Id: TableXml.cpp 146 2010-09-20 19:41:07Z volok-aleksej@yandex.ru $
*
* Copyright 2010 by Volokitin Alexey
* All rights reserved
*
*/
#include "Common/include.h"
#include "TableXml.h"

CTableXml g_tableXml;

CTableXml::CTableXml()
: doc("table.xml"){
	if(!doc.LoadFile(TIXML_ENCODING_UTF8)){
		TiXmlDeclaration decl("1.0", "UTF-8", ""); 
		doc.InsertEndChild(decl);
		TiXmlElement root("table");
		doc.InsertEndChild(root);
		doc.SaveFile();
	}
	Init();
}

CTableXml::~CTableXml(){
	Save();
}


int CTableXml::GetCellRowCy(int nId, int nType){
	std::map<int, std::map<int, int> >::iterator it = m_aCelsRow.find(nType);
	if(it != m_aCelsRow.end()){
		std::map<int, int>::iterator it1 = it->second.find(nId);
		if(it1 != it->second.end())
			return it1->second;
	}
	return 0;
}

void CTableXml::Init(){
	TiXmlElement* root = doc.RootElement();
	if(!root)
		return;
	for(TiXmlElement* element = root->FirstChildElement("cell_row"); element; element = element->NextSiblingElement("cell_row")){
		int id = 0, type = 0, cy = 0;
		element->Attribute("id", &id);
		element->Attribute("type", &type);
		element->Attribute("size", &cy);
		m_aCelsRow[type][id] = cy;
	}
	for(TiXmlElement* element = root->FirstChildElement("header"); element; element = element->NextSiblingElement("header")){
		int id = 0, cx = 0;
		element->Attribute("id", &id);
		element->Attribute("size", &cx);
		m_aHeader[id] = cx;
	}
}

int CTableXml::GetHeaderCx(int nId){
	std::map<int, int>::iterator it = m_aHeader.find(nId);
	if(it != m_aHeader.end())
		return it->second;
	return 0;
}

void CTableXml::SetCellRowCy(int nId, int nType, int nCy){
	m_aCelsRow[nType][nId] = nCy;
}

void CTableXml::SetHeaderCx(int nId, int nCx){
	m_aHeader[nId] = nCx;
}

void CTableXml::Save(){
	TiXmlElement* root = doc.RootElement();
	root->Clear();
	for(std::map<int, int>::iterator it = m_aHeader.begin(); it != m_aHeader.end(); it++){
		TiXmlElement elem("header");
		elem.SetAttribute("id", it->first);
		elem.SetAttribute("size", it->second);
		root->InsertEndChild(elem);
	}
	for(std::map<int, std::map<int, int> >::iterator it = m_aCelsRow.begin(); it != m_aCelsRow.end(); it++){
		for(std::map<int, int>::iterator it1 = it->second.begin(); it1 != it->second.end(); it1++){
			TiXmlElement elem("cell_row");
			elem.SetAttribute("id", it1->first);
			elem.SetAttribute("type", it->first);
			elem.SetAttribute("size", it1->second);
			root->InsertEndChild(elem);
		}
	}
	doc.SaveFile();
}
